import { getToken } from '@/utils/auth'
import { DataUrl } from '@/utils/request'

export function xmlRequest(url, method = 'POST', data, cb) {
  let xhr = new XMLHttpRequest()
  xhr.open(method, DataUrl() + url, true)
  xhr.setRequestHeader('Content-Type', 'application/json')
  xhr.setRequestHeader('Authorization', 'Bearer ' + getToken())
  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      if (cb) {
        cb(xhr.responseText, true)
      }
    }
  }.bind(this)

  let body = ''
  if (typeof data == 'string' && data.constructor == String) {
    body = data
  } else {
    body = JSON.stringify(data)
  }
  xhr.send(body)

  let callabck = (e) => {
    if (cb) {
      cb(e.target.responseText, false)
    }
  }
  // xhr.addEventListener("loadstart", callabck);
  // xhr.addEventListener("load", callabck);
  // xhr.addEventListener("loadend", callabck);
  xhr.addEventListener('progress', callabck)
  // xhr.addEventListener("error", callabck);
  // xhr.addEventListener("abort", callabck);
  return xhr
}
